package com.spring.common.web.service.impl;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.spring.common.web.dao.CommonApiMapper;
import com.spring.common.web.dao.CrmContactMapper;
import com.spring.common.web.dao.CrmCustomerMapper;
import com.spring.common.web.model.CrmContact;
import com.spring.common.web.model.CrmCustomer;
import com.spring.common.web.service.CommonService;
import com.spring.security.web.model.BaseResult;


@Service
public class CommonServiceImpl implements CommonService {
	@Resource
	private CommonApiMapper commonApiMapper;
	
	@Resource
	private CrmCustomerMapper crmCustomerMapper;
	
	@Resource
	private CrmContactMapper crmContactMapper;


	// 根据部门id查询kids_parkID
	@Override
	public String getKidParkIDByDeptID(String deptID) {
		String kids_park_id = commonApiMapper.getKidParkIDByDeptID(deptID);
		return kids_park_id;
	}
	
	@Override
	public BaseResult addCustomer(CrmCustomer crmCustomer) {		
		String crmCustomerID=UUID.randomUUID().toString();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String time = sdf.format(new Date());
		int random=(int)(Math.random()*10000000);
		
		String customernumber=time+random;
		
		crmCustomer.setId(crmCustomerID);
		crmCustomer.setCustomernumber(customernumber);
		
		//String customerNumber=this.createCustomerNumber("cc", "2");
		
		crmCustomer.setCustomernumber(customernumber);
		
		crmCustomerMapper.insert(crmCustomer);
		
		for(CrmContact crmContact:crmCustomer.getCrmContact()){
			List<CrmContact> list =crmContactMapper.selectByPhone(crmContact.getPhonenumber());
			if(list.size()>0){
				//老客户
				for(CrmContact c:list){
					c.setCuserid(crmContact.getCuserid());
					crmContactMapper.updateByPrimaryKeySelective(c);
				}
			}else{
				//新客户
				crmContact.setCrmCustomerid(crmCustomerID);
				crmContactMapper.insert(crmContact);
			}			
		}
		return null;
	}
	
	@Override
	public String createCustomerNumber(String title,String customerType) {
		
		String customerCount=crmCustomerMapper.getCustomerCount(customerType);
		
		String  customerNumber=title+customerCount;
		
		return customerNumber;
	}


}
